package com.ch4;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author woldier
 * @version 1.0
 * @description 同步交替运行问题
 * @date 2023/5/10 14:49
 **/
public class Demo12 {

    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();
        new Thread(()->{awaitSignal.print("a",a,b);},"a").start();
        new Thread(()->{awaitSignal.print("b",b,c);},"b").start();
        new Thread(()->{awaitSignal.print("c",c,a);},"c").start();
        TimeUnit.SECONDS.sleep(1);
        awaitSignal.tryLock();
        a.signal();
        awaitSignal.unlock();
    }

}
@Slf4j(topic = "c.Thread")
class AwaitSignal extends ReentrantLock {
    private int count;

    public AwaitSignal(int count) {
        this.count = count;
    }

    public void print(String s, Condition current,Condition next){
        for (int i = 0; i < count; i++) {
            this.tryLock();

            try {
                current.await();
                log.debug(s);
                next.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                this.unlock();
            }

        }

    }
}
